import React from 'react';
import { Routes, Route, Link, useNavigate, useLocation } from 'react-router-dom';
import { Layout, Menu, Button, theme, Avatar, Dropdown, message } from 'antd';
import { UserOutlined, DashboardOutlined, FileSearchOutlined, LogoutOutlined } from '@ant-design/icons';

// 页面组件
import Dashboard from './pages/dashboard';
import AuditList from './pages/audit';
import Login from './pages/login';
import { mockLogin } from './utils/http'; // 假设 mockLogin 函数在这里

// 样式
import './App.css';

const { Header, Content, Footer, Sider } = Layout;

const App: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [collapsed, setCollapsed] = React.useState(false);
  const [isLoggedIn, setIsLoggedIn] = React.useState(false); // 初始状态设为未登录
  const [userRole, setUserRole] = React.useState(''); // 新增角色状态

  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();


  // 模拟登录
  const handleLoginSuccess = async (username: string, password: string) => {
    try {
      const response = await mockLogin(username, password);
      if (response.success) {
        setIsLoggedIn(true);
        setUserRole(response.data.role);
        console.log("打印用户身份", response.data.role);
        navigate('/dashboard');
      } else {
        message.error('登录失败，请重试');
      }
    } catch (error) {
      console.error('登录失败:', error);
      message.error('登录失败，请重试');
    }
  };

  // 如果未登录，显示登录页面
  if (!isLoggedIn) {
    return <Login onLoginSuccess={handleLoginSuccess} />;
  }
  // 模拟退出登录
  const handleLogout = () => {
    setIsLoggedIn(false);
    setUserRole('');
    navigate('/login');
  };
  // 用户菜单项
  const userMenuItems = [
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      onClick: handleLogout,
    },
  ];
  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider collapsible collapsed={collapsed} onCollapse={(value) => setCollapsed(value)}>
        <div className="demo-logo-vertical" />
        <Menu
          theme="dark"
          defaultSelectedKeys={[location.pathname === '/' ? '/dashboard' : location.pathname]}
          mode="inline"
          items={[
            {
              key: '/dashboard',
              icon: <DashboardOutlined />,
              label: <Link to="/dashboard">仪表盘</Link>,
            },
            {
              key: '/audit',
              icon: <FileSearchOutlined />,
              label: <Link to="/audit">游记审核</Link>,
            },
          ]}
        />
      </Sider>
      <Layout>
        <Header style={{
          padding: 0, background: colorBgContainer, display: 'flex', // 使用 Flexbox 布局
          alignItems: 'center'
        }}>
          <div style={{ display: 'flex', justifyContent: 'flex-end', paddingRight: 20, alignItems: 'center', marginLeft: 'auto' }}>
            <Dropdown menu={{ items: userMenuItems }} placement="bottomRight">
              <Button type="text" icon={<Avatar icon={<UserOutlined />} />}>
                {userRole === 'admin' ? '管理员' : userRole === 'auditor' ? '审核员' : '未知角色'}
              </Button>
            </Dropdown>
          </div>
        </Header>
        <Content style={{ margin: '0 16px' }}>
          <div
            style={{
              padding: 24,
              minHeight: 360,
              background: colorBgContainer,
              borderRadius: borderRadiusLG,
              marginTop: 16,
            }}
          >
            <Routes>
              <Route path="/dashboard" element={<Dashboard />} />
              <Route path="/audit" element={<AuditList userRole={userRole} />} />
            </Routes>
          </div>
        </Content>
        <Footer style={{ textAlign: 'center' }}>
          旅游日记平台管理系统 ©{new Date().getFullYear()} 创建
        </Footer>
      </Layout>
    </Layout>
  );
};

export default App;